package cn.springstudio.springui.template;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import cn.springstudio.springui.R;

/**
 * 名称：<b>MainAdapter</b>
 * <p>作者：Spring Studio</p>
 * <p>版本：1.0</p>
 * <p>日期：2022/02/24 22:07</p>
 * <p>说明：</p>
 */
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {

    Context context;
    LayoutInflater inflater;
    OnGridListener listener;

    public GridAdapter(Context context, OnGridListener listener) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(inflater.inflate(R.layout.item_grid, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.update(position);
    }

    @Override
    public int getItemCount() {
        return listener.getItemCount();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.text_view);
            itemView.setOnClickListener(v -> listener.onItemClicked(getAdapterPosition()));
        }

        public void update(int position) {
            textView.setText(listener.getItem(position));
        }
    }

    public interface OnGridListener {
        int getItemCount();

        String getItem(int position);

        void onItemClicked(int position);
    }
}
